import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';
import { GroupRole } from '@/app/types/group';
// 创建群聊
export async function POST(req: NextRequest) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { name, description, members = [] } = await req.json();

    if (!name) {
      return NextResponse.json({ error: '群组名称不能为空' }, { status: 400 });
    }

    // 确保创建者自己也在成员列表中
    const allMemberIds = [...new Set([userId, ...members])];

    // 使用事务确保 Group 和 GroupMember 的一致性
    const newGroup = await prisma.$transaction(async (tx) => {
      const group = await tx.group.create({
        data: {
          name,
          description,
          ownerId: userId,
        },
      });

      // 批量创建群成员
      await tx.groupMember.createMany({
        data: allMemberIds.map(memberId => ({
          groupId: group.id,
          userId: memberId,
          role: memberId === userId ? GroupRole.OWNER : GroupRole.MEMBER,
        })),
      });
      
      // 创建一条系统消息，通知群聊已创建
      const conversation = await tx.conversation.create({
        data: {
          type: 'group',
          name: group.name,
          avatar: group.avatar,
          participants: {
            create: allMemberIds.map(memberId => ({
              userId: memberId,
            })),
          },
          messages: {
            create: {
              content: '群聊已创建',
              type: 'SYSTEM',
              senderId: userId,
            }
          },
          group: {
            connect: {
              id: group.id,
            }
          }
        }
      });

      return conversation;
    });

    return NextResponse.json(newGroup, { status: 201 });
  } catch (error) {
    console.error('创建群组失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}

export async function GET(req: NextRequest) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const groupMemberships = await prisma.groupMember.findMany({
      where: { userId: userId },
      include: {
        group: true, // 包含整个群聊的信息
      },
      orderBy: {
        group: {
          createdAt: 'desc',
        },
      },
    });

    const groups = groupMemberships.map((membership) => membership.group);

    return NextResponse.json(groups);
  } catch (error) {
    console.error('获取群组列表失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 